package jd.com;
import jd.util.ExcelFileFilter;
import jd.util.IdcardValidator;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.util.*;

/**
 * Created by wangpengzhi1 on 2018/7/5.
 */
public class RunListener implements ActionListener{


    private JTable jt_pool, jt_student;
    private ArrayList<Object[]> studentList;
    private ArrayList<Object[]> poolList;
    private OperUI ui;

    Object[] stuCol;
    Object[] nameCol;


    public RunListener(JTable jt_pool, JTable jt_student, OperUI ui) {
        this.ui = ui;
        this.jt_pool = jt_pool;
        this.jt_student = jt_student;
    }

    public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand().equals("importStudent")){
            jt_student.setName("stu");
            studentList = exportData(jt_student);
        }

        if(e.getActionCommand().equals("importPool")){
            jt_pool.setName("pool");
            poolList = exportData(jt_pool);
        }

        if(e.getActionCommand().equals("checkData")){
            ArrayList<Object> checkPoolList = getFailList(nameCol, poolList);
            ArrayList<Object> checkStuList =  getFailList(stuCol, studentList);
            ArrayList<Object> repeatPoolList = getRepeatDataList(nameCol, poolList);
            ArrayList<Object> repeatStuList =  getRepeatDataList(stuCol, studentList);

            if(CollectionUtils.isEmpty(checkPoolList) && CollectionUtils.isEmpty(checkStuList)){
                JOptionPane.showMessageDialog(ui, "数据校验通过！");
                return;
            }
            new MyJDialog(ui, checkStuList ,checkPoolList, repeatPoolList, repeatStuList,0).setVisible(true);
        }

        if(e.getActionCommand().equals("byId")){
            if(!findList()) return;
            new MyJDialog(ui, studentList ,poolList,stuCol, nameCol).setVisible(true);
        }

        if(e.getActionCommand().equals("reset")){
            poolList = new ArrayList<Object[]>();
            fillDataTableWithList(poolList, jt_pool, nameCol);
        }

        if(e.getActionCommand().equals("resetS")){
            studentList = new ArrayList<Object[]>();
            fillDataTableWithList(studentList, jt_student, stuCol);
        }

    }

    private ArrayList<Object> getFailList(Object[] colName, ArrayList<Object[]> checkList) {
        ArrayList<Object> failList = new ArrayList<Object>();
        if(colName != null  && CollectionUtils.isNotEmpty(checkList)){
            int index = -1;
            for(int i= 0; i < colName.length; i++){
                if(colName[i].toString().contains("身份证") || colName[i].toString().contains("证件号")){
                    index = i;
                    break;
                }
            }

            if(index == -1)  return  failList;

            for(Object[] obtStr : checkList){
                if(obtStr.length > index){
                    if(StringUtils.isEmpty(obtStr[index].toString()))
                        failList.add("存在空数据！序号：" + obtStr[0].toString());

                    else if(!IdcardValidator.cleckIdNumber(obtStr[index].toString()))
                        failList.add(obtStr[index]);
                }
            }
        }
        return failList;
    }



    private ArrayList<Object> getRepeatDataList(Object[] colName, ArrayList<Object[]> checkList) {
        ArrayList<Object> failList = new ArrayList<Object>();
        if(colName != null  && CollectionUtils.isNotEmpty(checkList)){
            List<Integer> indexList = new ArrayList<Integer>();
            for(int i= 0; i < colName.length; i++){
                if(colName[i].toString().contains("身份证") || colName[i].toString().contains("学籍号") || colName[i].toString().contains("证件号")){
                    indexList.add(i);
                }
            }
            if(CollectionUtils.isEmpty(indexList))  return  failList;
            for(Integer index : indexList){
                ArrayList<String> arr = new ArrayList<String>();
                for(Object[] obtStr : checkList){
                    if(StringUtils.isNotEmpty(obtStr[index].toString())){
                        if(arr.contains(obtStr[index].toString())){
                            failList.add(obtStr[index]);
                        }else{
                            arr.add(obtStr[index].toString());
                        }
                    }
                }
            }
        }
        return failList;
    }

    private ArrayList<Object[]> exportData(JTable showTable) {
        Object[] colName = null;
        ArrayList<Object[]> list = new ArrayList<Object[]>();
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setAcceptAllFileFilterUsed(false);
        fileChooser.addChoosableFileFilter(new ExcelFileFilter("xls"));
        //添加excel文件的过滤器
        int result = fileChooser.showOpenDialog(null);
        if(result == JFileChooser.APPROVE_OPTION)
        {
            try{
                FileInputStream inputStream  = new FileInputStream(fileChooser.getSelectedFile());
                Workbook xssfWorkbook;
                if(fileChooser.getSelectedFile().getName().endsWith("xls")){
                    xssfWorkbook =  new HSSFWorkbook(inputStream);
                }
                else {
                    xssfWorkbook =  new XSSFWorkbook(inputStream);
                }

                Sheet sheet = xssfWorkbook.getSheetAt(0);
                for(int i = 0; i <= sheet.getLastRowNum(); i++){
                    Row row = sheet.getRow(i);
                    if(colName != null && !StringUtils.isEmpty(getValue(0, row))){
                        Object[] obj = new Object[row.getLastCellNum()];
                        for(int m = 0; m < row.getLastCellNum(); m++){
                            obj[m] = getValue(m, row);
                        }
                        list.add(obj);
                    }
                    if(colName == null && !StringUtils.isEmpty(getValue(3, row))){
                        colName = new Object[row.getLastCellNum()];
                        for(int j = 0; j<row.getLastCellNum(); j++){
                            colName[j] = getValue(j, row);
                        }
                    }
                }
            }catch (Exception e1){
                e1.printStackTrace();
            }
        }
        if(showTable.getName().endsWith("stu")){
            stuCol = colName;
        }else {
            nameCol = colName;
        }
        fillDataTableWithList(list, showTable, colName);

        return list;
    }

    private boolean findList(){
        if (CollectionUtils.isEmpty(studentList)){
            JOptionPane.showMessageDialog(ui, "请导入学生数据信息！");
            return false;
        }
        if (CollectionUtils.isEmpty(poolList)){
            JOptionPane.showMessageDialog(ui, "请导入扶贫办数据信息！");
            return false;
        }
        return true;
    }

    private String getValue(int cellNum, Row row){
        if(row.getCell(cellNum) == null) return "";
        if(row.getCell(cellNum).getCellTypeEnum().getCode() == 0){
            return String.valueOf(row.getCell(cellNum).getNumericCellValue());
        }
        return  row.getCell(cellNum).getStringCellValue();
    }

    public  void fillDataTableWithList(ArrayList<Object[]> studentList,JTable jt_student, Object[] model){
        Vector vectorData = new Vector();
        for (Object[] objArr : studentList){
            Vector vector = new Vector();
            for (int i = 0; i< objArr.length; i++){
                vector.add(objArr[i]);
            }
            vectorData.add(vector);
        }
        Vector vectorheader = new Vector();
        if(model != null){
            for(Object name : model){
                vectorheader.add(name);
            }
        }
        DefaultTableModel defaultTableModel = new DefaultTableModel(vectorData, vectorheader);
        jt_student.setModel(defaultTableModel);
    }

}
